<?php
namespace Home\Controller;
use Think\Controller;
/**
 * 用户信息
 */
class ProfileController extends HomeController {
	private $user;
	private $password;
	/**
	 * 构造函数
	 */
	public function _initialize() {
		parent::_initialize();
		$this->user = M('User');
		$this->password = M('Password');
	}
	/**
	 * 帐号信息
	 */
	public function index() {
		$map = array();
		$map['uid'] = $this->uid;
		$data = $this->user->where($map)->field('uid,email,password,register_time,register_ip,login_count,last_login_time,last_login_ip,timeout')->find();
		if (IS_POST) {
			$timeout = I('post.timeout');
			$password = I('post.password');
			$new_password = I('post.new_password');
			$data_user = array();
			if (1 > $timeout || 15 < $timeout) {
				$this->error('你填写的超时保护时间不在1~15分钟之内');
			}
			$data_user['timeout'] = $timeout;
			if ('' != $password || '' != $new_password) {
				if ($password != pwd_decode($data['password'])) {
					$this->error('你填写的原密码错误');
				}
				
				$password_len = strlen($new_password);
				if (6 > $password_len) {
					$this->error('新密码至少6位');
				}elseif (20 < $password_len) {
					$this->error('新密码不能超过20位');
				}
				$level = 0;
				// 数字
				if (1 == preg_match('/\d/', $new_password)) {
					$level++;
				}
				// 小写字母
				if (1 == preg_match('/[a-z]/', $new_password)) {
					$level++;
				}
				// 大写字母
				if (1 == preg_match('/[A-Z]/', $new_password)) {
					$level++;
				}
				// 特殊字符~!@#$%^&*()_<>-
				if (1 == preg_match('/[~!@#$%^&*()_<>\-]/', $new_password)) {
					$level++;
				}
				if (3 > $level) {
					$this->error('新密码至少包含数字、小写字母、大写字母和特殊字符的三种形式');
				}
				$data_user['password'] = pwd_encode($new_password);
			}
			if (false !== $this->user->where($map)->save($data_user)) {
				if (isset($data_user['password'])) {
					// 设置新密码后，需要重新登录
					$jumpUrl = U('User/logout');
				}else {
					$jumpUrl = '';
				}
				$this->success('保存成功', $jumpUrl);
			}else {
				$this->error('保存失败');
			}
		}else {
			$map_password = array();
			$map_password['uid'] = $this->uid;
			$map_password['status'] = 1;
			$data['password_num'] = $this->password->where($map)->count();
			
			$this->assign('data', $data);
			$this->display();
		}
	}
}